import React, { PureComponent as Component } from 'react';
import {
  Form,
  Input,
  Icon,
  Button,
  Row,
  Col,
  message,
  Select
} from 'antd';
const { TextArea } = Input;

import PropTypes from 'prop-types';
import {
  updateProject,
  delProject,
  getProject,
  upsetProject
} from '../../../reducer/modules/dubboProject';
import { fetchGroupMsg,fetchGroupList } from '../../../reducer/modules/group';
import { setBreadcrumb } from '../../../reducer/modules/user';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
const FormItem = Form.Item;
import constants from '../../../constants/variable.js';
import { nameLengthLimit } from '../../../common';
import '../Setting/Setting.scss';
// layout
const formItemLayout = {
  labelCol: {
    lg: { offset: 1, span: 3 },
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    lg: { span: 19 },
    xs: { span: 24 },
    sm: { span: 14 }
  },
  className: 'form-item'
};
const Option = Select.Option;


@connect(
  state => {
    return {
      projectList: state.dubboProject.projectList,
      groupList: state.group.groupList,
      projectMsg: state.dubboProject.currProject,
      currGroup: state.group.currGroup
    };
  },
  {
    updateProject,
    delProject,
    getProject,
    fetchGroupMsg,
    upsetProject,
    fetchGroupList,
    setBreadcrumb
  }
)
@withRouter
class ProjectMessage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      projectMsg: {}
    };
  }
  static propTypes = {
    projectId: PropTypes.number,
    form: PropTypes.object,
    updateProject: PropTypes.func,
    delProject: PropTypes.func,
    getProject: PropTypes.func,
    history: PropTypes.object,
    fetchGroupMsg: PropTypes.func,
    upsetProject: PropTypes.func,
    groupList: PropTypes.array,
    projectList: PropTypes.array,
    projectMsg: PropTypes.object,
    fetchGroupList: PropTypes.func,
    currGroup: PropTypes.object,
    setBreadcrumb: PropTypes.func,
    match: PropTypes.object
  };

  // 确认修改
  handleOk = e => {
    e.preventDefault();
     this.props.form.validateFields((err, values) => {
       if(values.childbase && values.childbase.length !== 2) {
         message.error("渠道前置应为2位数字!")
       }
       else if (!err) {
        const { updateProject, projectMsg } = this.props;
        let assignValue = Object.assign(values);
        assignValue.id=projectMsg._id;
        console.log(assignValue);

        updateProject(assignValue).then(res => {
            if (res.payload.data.errcode == 0) {
              this.props.getProject(this.props.projectMsg._id);
              message.success('修改成功! ');

             this.props.fetchGroupMsg(assignValue.groupid);
            }
          })
          .catch(() => {});          }
        });

  };

  delOk = () =>{
    let that = this;
    that.props.delProject(that.props.projectMsg._id).then(res => {
      if (res.payload.data.errcode == 0) {
        message.success('删除成功!');
        that.props.history.push('/group/' + that.props.projectMsg.groupid);
      }
    });
  }


  async componentWillMount() {
    await this.props.fetchGroupList();
    await this.props.fetchGroupMsg(this.props.projectMsg.groupid);

  }

  render() {
    const { projectMsg, currGroup } = this.props;
    const { getFieldDecorator } = this.props.form;
    const selectDisbaled = projectMsg.role === 'owner' || projectMsg.role === 'admin';
    let initFormValues = {};
    const {
      cnname,
      enname,
      dgroup,
      onlinedate,
      groupid,
      desc,
      expname,
      childbase
    } = projectMsg;
    initFormValues = {
      cnname,
      enname,
      dgroup,
      onlinedate,
      groupid,
      desc,
      expname,
      childbase
    };
    return (
      <div>
        <div className="m-panel" style={{marginLeft:'24px',marginRight:'24px'}}>
          <Row className="project-setting">
            <Col xs={6} lg={{ offset: 1, span: 3 }} className="setting-logo">
              <Icon
                  type={projectMsg.icon || 'star-o'}
                  className="ui-logo"
                  style={{
                    backgroundColor:
                      constants.PROJECT_COLOR[projectMsg.color] || constants.PROJECT_COLOR.blue
                  }}
              />
            </Col>
            <Col xs={18} sm={15} lg={19} className="setting-intro">
              <h2 className="ui-title">
                {(currGroup.group_name || '') + ' / ' + (initFormValues.cnname || '')}
              </h2>
              {/* <p className="ui-desc">{projectMsg.desc}</p> */}
            </Col>
          </Row>
          <hr className="breakline" />
          <Form>
            <FormItem {...formItemLayout} label="项目ID">
              <span>{this.props.projectMsg._id}</span>
            </FormItem>
            <FormItem {...formItemLayout} label="项目名称">
              {getFieldDecorator('cnname', {
                    initialValue: initFormValues.cnname,
                    rules: nameLengthLimit('项目')
                })(<Input />)}
            </FormItem>
            <FormItem {...formItemLayout} label="项目简称">
              {getFieldDecorator('enname', {
                    initialValue: initFormValues.enname,
                    rules: nameLengthLimit('简称')
                })(<Input />)}
            </FormItem>
            <FormItem {...formItemLayout} label="Dubbo组">
              {getFieldDecorator('dgroup', {
                    initialValue: initFormValues.dgroup,
                    rules: nameLengthLimit('Dubbo组')
                })(<Input />)}
            </FormItem>
            <FormItem {...formItemLayout} label="上线日期">
              {getFieldDecorator('onlinedate', {
                initialValue: initFormValues.onlinedate,
                    rules: nameLengthLimit('上线日期')
                })(<Input />)}
            </FormItem>
            {/* ttc add*/}
            <FormItem {...formItemLayout} label="异常定义">
              {getFieldDecorator('expname', {
                initialValue: initFormValues.expname
                // ,
                // rules: [
                //   {
                //     required: true,
                //     message: '请输入异常定义!'
                //   }
                // ]
              })(<Input />)}
            </FormItem>
            <FormItem {...formItemLayout} label="渠道前置定义">
              {getFieldDecorator('childbase', {
                initialValue: initFormValues.childbase
                // ,
                // rules: [
                //   {
                //     required: true,
                //     message: '请输入渠道前置定义!应为两位数字'
                //   }
                // ]
              })(<Input />)}
            </FormItem>
            {/*ttc add ^^^^*/}
            <FormItem {...formItemLayout} label="所属分组">
              {getFieldDecorator('groupid', {
                    initialValue: initFormValues.groupid,
                    rules: [
                        {
                            required: true,
                            message: '请选择项目所属的分组!'
                        }
                    ]
                })(
                  <Select disabled={!selectDisbaled}>
                    {this.props.groupList.map((item, index) => (
                      <Option value={item._id} key={index}>
                        {item.group_name}
                      </Option>
                        ))}
                  </Select>
                )}
            </FormItem>
            <hr className="breakline" />
            <FormItem {...formItemLayout} label="描述">
              {getFieldDecorator('desc', {
                initialValue:initFormValues.desc,
                    rules: [
                        {
                            required: false,
                            message: '描述不超过144字!',
                            max: 144
                        }
                    ]
                })(<TextArea rows={4} />)}
            </FormItem>
          </Form>

          <div className="btnwrap-changeproject" style={{marginLeft:"0px",marginRight:"0px"}}>
            <Button
              className="m-btn btn-save"
              icon="save"
              type="primary"
              size="large"
              style={{ marginRight:'10px' }}
              onClick={this.handleOk}
            >
              保 存
            </Button>
            {projectMsg.role === 'owner' || projectMsg.role === 'admin' ? (
              <Button
                  className="m-btn btn-save"
                  icon="delete"
                  type="primary"
                  size="large"
                  onClick={this.delOk}
                >
                  删除
              </Button>) : null}
          </div>
        </div>
      </div>
    );
  }
}

export default Form.create()(ProjectMessage);
